#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    // 创建一个文件来存储amixer的输出
    FILE *fp1 = fopen("/tmp/volume.txt", "w+");
    if (fp1 == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    
    // 打开管道，通过amixer命令获取音量
    FILE *fp = popen("amixer get Master > /tmp/volume.txt", "w");
    if (fp == NULL) {
        perror("popen");
        exit(EXIT_FAILURE);
    }
  
    // 关闭管道
    pclose(fp);
    
    // 打开文件以读取音量数值
    fp = fopen("/tmp/volume.txt", "rb");
    if (fp == NULL) {
        perror("fopen");
        fclose(fp);
        exit(EXIT_FAILURE);
    }
    
    char buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    size_t bytes_read = fread(buffer, sizeof(char), sizeof(buffer) - 1, fp);
    fclose(fp);
    
    
    // 打印获取到的音量信息
    //printf("Current volume: %s\n", buffer);

    // 设置音量为50%
    fp = popen("amixer set -c 0 Master 50) > /tmp/volume.txt", "w");
    if (fp == NULL) {
        perror("popen");
        exit(EXIT_FAILURE);
    }
    
    // 解析音量数值
    char *volume_str = strstr(buffer, "Front Left: Playback ");
    if (volume_str != NULL) {
        volume_str += strlen("Front Left: Playback ");
        char *end_ptr = volume_str;
        while (*end_ptr == ' ') {
            end_ptr++;
        }
        int volume = atoi(end_ptr);
        printf("Volume in absolute value: %d\n", volume);
    } else {
        printf("Volume information not found.\n");
    }
    
    // 确保amixer命令的输出被发送到音频混合器
    pclose(fp);

    // 删除临时文件
    remove("/tmp/volume.txt");

    return 0;
}
